#coding:utf-8

"""
@author:自之梦 10061661
@time: 17/11/11 上午11:11
#奇门接口
"""
import random
import time
import functools
import requests
import threading
import uuid
import re
import MySQLdb


result_order = []
base_url = "http://10.10.111.240:7510"
time_str = time.strftime("%Y-%m-%d %H:%M:%S")
time_rod = str(uuid.uuid1())[15:25]

def build_uri(endpoint):
    return "/".join([base_url, endpoint])


class MyThread(threading.Thread):
    def __init__(self, func, args="", name=""):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args

    def run(self):
        self.func(*self.args)
		
  
def Ma5_Val(str, val_type=""):
    #MD5加密,用于接口签名
    #默认小写，大写需要传upper
    import hashlib
    import types
    if type(str) is types.StringType:
        md5 = hashlib.md5()
        md5.update(str)
        if val_type == "upper":
            return md5.hexdigest().upper()
        else:
            return md5.hexdigest()
    else:
        return "errorCode: parameter1 must be str."


def Data_Key_Sort(data):
    #字典key排序,   用于接口签名
    #结果效果：aaa1a1bbcc
    result=sorted(data.items(), key=lambda item:item[0])
    test=""
    for i in result:
        test = test+ "".join(i)
    return test


def Key_Val_Sort(data):
    #字典key排序,用于接口签名
    #结果效果：a=a&a1=a1&b=b&c=c
    result=sorted(data.items(), key=lambda item:item[0])
    test = []
    for i in result:
        result = "=".join(i)
        test.append(result)

    return "&".join(test)


def log(fuc):
    #日志监控
    @functools.wraps(fuc)
    def wrapper(*args, **kwargs):
        print "%s fuc start ..." % fuc.__name__
        t1 = time.time()
        result = fuc(*args, **kwargs)
        t2 = time.time()
        time_Val = int(float( '%.3f' % (t2 - t1))*1000)
        print "%s fuc end ..." % fuc.__name__
        print "{1} fuc total running: {0}ms".format(str(time_Val), fuc.__name__)
        print "-"*32
        print "response: ", result,"\n"
        return result
    return wrapper


def dataHeader(ordertype="deliveryorder.create", customerId="LJJ-T"):
    
    testdata = {"method":ordertype,
                "format":"xml",
                "app_key":"alogalog",
                "v":"2.4",
                "sign_method":"md5",
                "customerId":"LJJ-T",
                "notifyId":str(time_rod),
                "timestamp":str(time_str)}
    return testdata


@log
def qm_create_order():
    """
    method: 订单创建，
    商家：ljj商家，
    """
    global time_str, time_rod
    time_str = time.strftime("%Y-%m-%d %H:%M:%S")
    time_rod = str(uuid.uuid1())[10:25] + str(random.randint(10000, 90000))
    testdata = dataHeader("deliveryorder.create")
    content = '<?xml version="1.0" encoding="UTF-8"?><request><deliveryOrder><deliveryOrderCode>{time_rod}</deliveryOrderCode><orderType>JYCK</orderType>\
<warehouseCode>LJJHN</warehouseCode>\
<sourcePlatformCode>OTHER</sourcePlatformCode><createTime>{timestr}</createTime><placeOrderTime>{timestr}</placeOrderTime>\
<operateTime>{timestr}</operateTime><shopNick>强生中国旗舰店</shopNick><logisticsCode>YTO</logisticsCode><senderInfo><name>test</name>\
<mobile>13800138000</mobile><province>澳门</province><city>离岛</city><detailAddress>testdetailAddress</detailAddress></senderInfo><receiverInfo>\
<name>我想说</name><mobile>15001165221</mobile><province>澳门</province><city>离岛</city><detailAddress>办事处</detailAddress></receiverInfo></deliveryOrder>\
<orderLines>\
<orderLine><orderLineNo>{time_rod}1</orderLineNo><ownerCode>LJJ-T</ownerCode><itemCode>jittest_001</itemCode><inventoryType>ZP</inventoryType><planQty>1</planQty></orderLine>\
</orderLines></request>'.format(time_rod=time_rod, timestr=time_str)
    testdata["sign"] = Ma5_Val(Data_Key_Sort(testdata) + content, "upper")
    url = url = build_uri("qm-portal/rest.htm?{0}").format(Key_Val_Sort(testdata))  

    r = requests.post(url, content)
    order_id = ''.join(re.findall(r'<deliveryOrderId>(.+?)</deliveryOrderId>',r.text.encode('utf-8')))
    if r.status_code and order_id:
        result_dit = {}
        result_dit["orderId"] = order_id
        result_order.append(result_dit)
        return sorted(result_order), len(result_order)
    else:
       return r.text,"\n>>>>>>deliveryOrderCode: {0}".format(time_rod)


def canmel_order(orderCode, ordertype, warehouseCode="", ownerCode=""):

    """
    method: 拦截订单，
    商家：ljj商家
    """
    testdata = dataHeader("order.cancel")
    content = '<?xml version="1.0" encoding="utf-8"?><request><warehouseCode>{warehouseCode}</warehouseCode>\
<ownerCode>{ownerCode}</ownerCode><orderCode>{orderCode}</orderCode><orderId>{orderCode}</orderId>\
<orderType>{orderType}</orderType><cancelReason>test</cancelReason>\
</request>'.format(orderCode=orderCode, orderType=ordertype, warehouseCode=warehouseCode, ownerCode=ownerCode)

    testdata["sign"] = Ma5_Val(Data_Key_Sort(testdata) + content, "upper")
    url = build_uri("qm-portal/rest.htm?{0}").format(Key_Val_Sort(testdata))    

    r = requests.post(url, content)
    print r.url
    print "\n"
    return r.text

def getConnect():
    print "connection DB start..."
    try:
        db = MySQLdb.connect(
            host="10.10.111.240",
            port = 3306,
            user = "omsmanger",
            passwd = "alog@123",
            db = "oms",
            charset='utf8'
            )
        return True, db 
    except Exception as e:
        #print e
        return False, e
        

def get_sku_for_Db():

    db = getConnect()
    if db[0]:
        cursor = db[1].cursor()
    else:
        return "connection DB failed: {0}.".format(db[1])
    
    
    #汇总订单的状态
    sql = {"CHECK" : "SELECT COUNT(*) FROM sale_order WHERE `status`='CHECK' AND merchant_id=1 ;",
           "INIT" : "SELECT COUNT(*) FROM sale_order WHERE `status`='INIT' AND merchant_id=1 ;",
           "DELIVERY" : "SELECT COUNT(*) FROM sale_order WHERE `status`='DELIVERY' AND merchant_id=1 ;",
           "total" : "SELECT COUNT(*) FROM sale_order WHERE  merchant_id=1 ;"}
    
    order_total_num = {}
    try:
        for k,v in sql.items():
            cursor.execute(v)
            result = cursor.fetchall()#获取查询结果
            if result:
                for x in result:
                    for y in x:
                        order_total_num[k]=y
            else:
                return False
    except Exception:
        #如果发生异常，则回滚  
            print("发生异常",Exception)  
            db[1].rollback()  
    finally:  
        cursor.close()
        db[1].close()
    return order_total_num
        

if __name__ == "__main__":
    
    #print canmel_order("OS20171120000049","JYCK", "LJJHN", "LJJ-T")

    print get_sku_for_Db()#get_sku_for_Db()
    """
    threads = []
    NUM=50
    for i in range(NUM):
        t = MyThread(qm_create_order, name=qm_create_order.__name__)
        threads.append(t)

    for i in range(NUM):
        threads[i].start()
        #print threading.current_thread()
    for i in range(NUM):
        threads[i].join()
    """
    